import * as THREE from 'three'
import { Mesh } from 'three'
import createApp from '../../core'

async function createShaderMaterial (dom: HTMLElement) {
  const { camera, scene } = createApp(dom)

  camera.position.set(-150, 100, 120)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const vertexShader = `
  varying vec3 vPosition;
  varying vec2 vUV;
  void main()
  {
      vPosition = position;
      vUV = uv;
      vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
      gl_Position = projectionMatrix * mvPosition;
  }`

  const fragmentShader = `
  varying vec3 vPosition;
  varying vec2 vUV;
  uniform vec3 uColor1;
  uniform vec3 uColor2;
  uniform vec3 uColor3;
  uniform sampler2D uTexture;
  void main( void ) {
      vec3 vCenter = vec3(0.0, 0.0, 0.0);
      if (vPosition.y < 5.0) {
        gl_FragColor = vec4( uColor1, 1.0 );
      } else {
        gl_FragColor = vec4( uColor2, 1.0 );
      }
      if (vPosition.y == 25.0 || vPosition.y == -25.0) {
        float len = distance(vCenter, vPosition);
        if (len < 30.0) {
            gl_FragColor = vec4( uColor3, 1.0 );
        }
      }
      if (vPosition.z == 25.0) {
        gl_FragColor = texture2D(uTexture, vUV);
      }
  }
  `
  const loader = new THREE.TextureLoader()
  const img = await import('@/assets/material/tile.jpg')
  loader.load(img.default, texture => {
    const geometry = new THREE.BoxGeometry(50, 50, 50)
    const material = new THREE.ShaderMaterial({
      uniforms: {
        uColor1: {
          value: new THREE.Color(0.0, 1.0, 1.0)
        },
        uColor2: {
          value: new THREE.Color(1.0, 1.0, 0.0)
        },
        uColor3: {
          value: new THREE.Color(0.0, 0.0, 0.0)
        },
        uTexture: {
          value: texture
        }
      },
      vertexShader,
      fragmentShader
    })
    const mesh = new Mesh(geometry, material)
    scene.add(mesh)
  })
}

export {
  createShaderMaterial
}
